<template>
  <div class="container">
    <div class="holiday-list">
      <!-- 假期列表内容 -->
      <div class="module-title">假期列表</div>
      <div class="date-box" id="list-group-item">
        <div class="flex-b box list-group-item" v-for="item in list" :key="item.name">
          <div>{{ item.name }}</div>
          <div class="circle" :class="item.color">{{ item.value }}</div>
        </div>
      </div>
    </div>
    <div class="calendar">
      <!-- 日历内容 -->
      <FullCalendar ref="fullCalendar" :options="calendarOptions"/>
    </div>
    <EventDetailDialog
      :visible.sync="showEventDetail"
      :event="selectedEvent"
      @edit="handleEventEdit"
      @delete="handleEventDelete"
    />
  </div>
</template>

<script>
import { holidayItem } from '@/api/methodsApi' // 项目中接口文件引入
import moment from 'moment'
import FullCalendar from '@fullcalendar/vue'
import dayGridPlugin from '@fullcalendar/daygrid'
import interactionPlugin, { Draggable } from '@fullcalendar/interaction'
import timeGridPlugin from '@fullcalendar/timegrid'
import multiMonthPlugin from '@fullcalendar/multimonth'  // 添加这行
import EventDetailDialog from './components/EventDetailDialog.vue'

export default {
  name: 'TradingTimeManage',
  components: {
    FullCalendar,
    EventDetailDialog
  },
  data() {
    return {
      eventEl: null,
      calendarOptions: {
        plugins: [
          dayGridPlugin, 
          timeGridPlugin, 
          interactionPlugin,
          multiMonthPlugin  // 添加插件
        ],
        firstDay: 1,
        headerToolbar: {
          left: 'prev,next today',
          center: 'title',
          right: 'multiMonthYear,dayGridMonth,timeGridWeek'  // 修改这行
        },
        buttonText: {
          today: '今天',
          multiMonthYear: '年',  // 修改这里，将按钮文本改为"年"
          month: '月',
          week: '周'
        },
        initialView: 'dayGridMonth',
        locale: 'zh-cn',
        selectable: true,
        slotMinutes: 15,
        editable: true, // 允许编辑事件
        droppable: true,
        dropAccept: '.list-group-item',
        drop: this.handleExternalDrop,
        eventReceive: this.handleEventReceive,  // 添加这一行
        eventDrop: this.handleEventDrop,      // 添加事件拖动处理器
        eventResize: this.handleEventResize,   // 保持事件可以调整大小
        customButtons: {
          // 自定义按钮配置
        },
        titleFormat: {
          year: 'numeric',
          month: 'long',
          day: 'numeric'
        },
        events: [], // 添加 events 属性
        eventClick: this.handleEventClick, // 添加事件点击处理
        eventDragStop: this.handleEventDragStop, // 添加事件拖动停止的处理器
        dragRevertDuration: 0,        // 添加：减少拖回动画时间
        dragScroll: true,             // 添加：允许拖动时滚动
        eventDragMinDistance: 5,
        longPressDelay: 50,            // 降低长按延迟
        eventLongPressDelay: 50,       // 降低事件长按延迟
        defaultTimedEventDuration: '01:00:00',
        snapDuration: '00:15:00',
        dragSnapGrid: {                // 添加网格对齐
          x: 1,
          y: 1
        },
        eventOverlap: false,
        eventTimeFormat: {
          hour: '2-digit',
          minute: '2-digit',
          hour12: false
        },
        eventConstraint: {
          startTime: '00:00',
          endTime: '24:00'
        },
        eventDisplay: 'block',
        displayEventEnd: true,
        nextDayThreshold: '00:00:00',
        dayMaxEventRows: true,
        dayMaxEvents: true,
        slotMinTime: "00:00:00",
        slotMaxTime: "24:00:00",
        // 添加多月视图配置
        views: {
          multiMonthYear: {
            type: 'multiMonth',
            duration: { months: 12 },
            multiMonthMaxColumns: 3,    // 最大列数
            multiMonthMinWidth: 350,    // 每个月的最小宽度
            multiMonthTitleFormat: { 
              month: 'long', 
              year: 'numeric' 
            }
          }
        },
        // 添加视图特定设置
        monthMode: true,
        fixedWeekCount: false,
        showNonCurrentDates: false,
        // 添加视图变化监听
        datesSet: this.handleDatesSet,
      },
      // 案例数据
      list: [
        { name: '活动1', color: 'blue', value: 1 },
        { name: '活动2', color: 'green', value: 2 }
      ],
      showTimePicker: false,
      selectedEvent: null,
      previousViewType: null, // 添加这个属性来跟踪上一次的视图类型
      showEventDetail: false,
    }
  },
  mounted() {
    var containerEl = document.getElementById('list-group-item');
    new Draggable(containerEl, {
      itemSelector: '.list-group-item',
      delay: 50,                      // 添加：降低拖动延迟
      mirror: {
        constrainTo: 'body',          // 限制拖动范围
        xAxis: true,
        yAxis: true
      },
      autoScroll: true,               // 启用自动滚动
      scrollSpeed: 20,                // 设置滚动速度
      scrollSensitivity: 30,          // 设置滚动灵敏度
      eventData: function(eventEl) {    // 添加：优化拖拽数据处理
        return {
          title: eventEl.innerText,
          create: false
        };
      },
      mirrorSelector: '.list-group-item', // 添加：指定镜像元素
    })
    this.holidayEvent()
  },
  methods: {
    prevMethod() {
      this.$refs.fullCalendar.getApi().prev()
      this.holidayEvent()
    },
    nextMethod() {
      this.$refs.fullCalendar.getApi().next()
      this.holidayEvent()
    },
    todayMethod() {
      this.$refs.fullCalendar.getApi().today()
      this.holidayEvent()
    },
    holidayEvent() {
      try {
        const calendar = this.$refs.fullCalendar.getApi();
        const currentView = calendar.view;
        const renderRange = currentView.currentStart && currentView.currentEnd ? {
          start: currentView.currentStart,
          end: currentView.currentEnd
        } : {
          start: new Date(),
          end: new Date()
        };
        
        this.start = Date.parse(moment(renderRange.start).format());
        this.end = Date.parse(moment(renderRange.end).format());
        
        holidayItem({ start: this.start, end: this.end }).then((res) => {
          if (res.status === '200') {
            const data = res.data
            const arr = []
            data.forEach(item => {
              const obj = {
                id: item.id,
                title: item.name,
                start: item.day,
                end: item.dayEnd,
                allDay: true,
                backgroundColor: item.name === '工作日' ? 'green' : '#3788d8'
              }
              arr.push(obj)
            })
            this.calendarOptions.events = arr
          }
        })
      } catch (error) {
        console.error('Error in holidayEvent:', error);
      }
    },
    handleExternalDrop(dropInfo) {
      try {
        const draggedText = dropInfo.draggedEl.textContent.trim();
        const eventItem = this.list.find(item => 
          draggedText.includes(item.name)
        );
        
        if (eventItem) {
          const startDate = dropInfo.date;
          const currentView = dropInfo.view.type;
          
          // 判断拖放位置
          let isAllDay = false;
          let newStart = new Date(startDate);
          let newEnd = new Date(startDate);
          
          // 处理不同视图类型的拖放逻辑
          if (currentView === 'timeGridWeek') {
            // 在周视图中，根据拖放位置决定是否为全天事件
            isAllDay = dropInfo.resource?.allDay || dropInfo.allDay;
            
            if (isAllDay) {
              // 全天事件处理
              newStart.setHours(0, 0, 0);
              newEnd.setHours(23, 59, 59);
            } else {
              // 非全天事件处理
              const hour = startDate.getHours();
              const minute = Math.floor(startDate.getMinutes() / 15) * 15;
              newStart.setHours(hour, minute, 0);
              newEnd = new Date(newStart.getTime() + 3600000); // 添加一小时
            }
          } else {
            // 月视图和其他视图默认设置
            isAllDay = currentView === 'dayGridMonth';
            if (isAllDay) {
              newStart.setHours(0, 0, 0);
              newEnd.setHours(23, 59, 59);
            } else {
              newStart.setHours(9, 0, 0); // 默认设置为上午9点
              newEnd = new Date(newStart.getTime() + 3600000);
            }
          }
          
          const newEvent = {
            id: Date.now(), // 添加唯一ID
            title: eventItem.name,
            start: newStart,
            end: newEnd,
            backgroundColor: eventItem.color === 'green' ? 'green' : '#3788d8',
            allDay: isAllDay
          };
          
          const calendar = this.$refs.fullCalendar.getApi();
          const addedEvent = calendar.addEvent(newEvent);
          
          // 打开时间设置对话框
          this.selectedEvent = addedEvent;
          this.showTimePicker = true;
        }
      } catch (error) {
        console.error('拖拽处理出错：', error);
        this.$message.error('创建事件失败，请重试');
      }
    },

    handleEventReceive(info) {
      // 确保新事件被正确接收
      const event = info.event;
      if (!event.id) {
        event.setProp('id', Date.now().toString());
      }
      this.selectedEvent = event;
      this.showTimePicker = true;
    },

    handleEventDrop(info) {
      // 处理现有事件的拖动，不影响新事件
      console.log('Event was moved', info.event)
    },

    handleEventResize(info) {
      // 处理现有事件的大小调整，不影响新事件
      console.log('Event was resized', info.event)
    },
    handleEventClick(info) {
      this.selectedEvent = info.event;
      this.showEventDetail = true;  // 显示详情弹窗而不是直接显示编辑弹窗
    },
    updateEventTime(eventData) {
      if (this.selectedEvent) {
        try {
          // 更新事件属性
          this.selectedEvent.setProp('title', eventData.title);
          
          // 转换日期字符串为 Date 对象
          const startDate = moment(eventData.start).toDate();
          const endDate = moment(eventData.end).toDate();
          
          this.selectedEvent.setDates(
            startDate,
            endDate,
            { allDay: eventData.allDay }
          );
          this.selectedEvent.setProp('backgroundColor', eventData.backgroundColor);
          
          console.log('Event updated:', {
            id: this.selectedEvent.id,
            ...eventData
          });
        } catch (error) {
          console.error('Error updating event:', error);
        }
      }
    },
    handleEventDelete(eventId) {
      const event = this.$refs.fullCalendar.getApi().getEventById(eventId);
      if (event) {
        event.remove();
        // 可以在这里添加与后端同步的逻辑
        console.log('Event deleted:', eventId);
      }
    },
    handleEventDragStop() {
      // 空方法，保持事件可以拖动
    },
    // 添加视图日期处理方法
    handleDatesSet() {
      const calendar = this.$refs.fullCalendar.getApi();
      const currentView = calendar.view;
      
      // 只有在切换到年视图时设置到年初
      if (currentView.type === 'multiMonthYear' && this.previousViewType !== 'multiMonthYear') {
        const currentYear = new Date().getFullYear();
        setTimeout(() => {
          calendar.gotoDate(new Date(currentYear, 0, 1));
        }, 0);
      } 
      // 从年视图切换到其他视图时，跳转到当前日期
      else if (this.previousViewType === 'multiMonthYear' && currentView.type !== 'multiMonthYear') {
        setTimeout(() => {
          calendar.today();
        }, 0);
      }
      
      // 更新前一个视图类型
      this.previousViewType = currentView.type;
    },
    handleEventEdit() {
      this.showEventDetail = false;
      this.showTimePicker = true;  // 打开时间编辑器
    },
  }
}
</script>

<style lang="scss" scoped>
.container {
  display: flex;
  padding: 20px;
  gap: 20px; // 添加组件之间的间距
  isolation: isolate;
  contain: content;
}

.holiday-list {
  flex: 1;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.calendar {
  flex: 5;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.module-title {
  font-size: 16px;
  font-weight: bold;
  padding: 10px 0;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 15px;
}

.circle {
  background-color: #3788d8;
  border-radius: 10px;
  color: #fff;
  display: inline-block;
  font-size: 12px;
  height: 18px;
  line-height: 18px;
  padding: 0 6px;
  text-align: center;
  white-space: nowrap;
  border: 1px solid #fff;
}
.blue {
  background-color: #3788d8;
}
.green{
  background-color: green;
}
.date-box {
  border-radius: 5px;
  padding: 10px 0;
}
.box {
  margin-top: 10px;
  border: 1px solid #ebeef5;
  padding: 10px 20px;
  border-radius: 5px;
  transition: all 0.3s;

  &:hover {
    background-color: #f5f7fa;
  }
}

.is-selected {
  color: #1989FA;
}

:deep(.fc) {
  // FullCalendar 内部样式调整
  .fc-header-toolbar {
    padding: 10px 0;
  }
  .fc-event {
    cursor: grab;
    touch-action: none;
    will-change: transform;
    transform: translateZ(0);
    backface-visibility: hidden;
    
    &:active {
      cursor: grabbing;
    }
  }
  
  .fc-event-dragging {
    opacity: 0.8;
  }
}

.list-group-item {
  cursor: grab;
  touch-action: none;  // 防止触摸设备的默认行为
  will-change: transform;  // 添加：优化性能
  transform: translateZ(0); // 添加：启用硬件加速
  backface-visibility: hidden;
  -webkit-font-smoothing: subpixel-antialiased;
  
  &:active {
    cursor: grabbing;
  }
}

// 优化拖动时的视觉效果
:deep(.fc-event-dragging),
:deep(.fc-event.fc-dragging) {
  opacity: 0.9;
  transform: scale(1.02);
  transition: none !important;        // 移除过渡效果提高响应速度
  pointer-events: none;              // 防止拖动时的干扰
  z-index: 9999 !important;          // 确保拖动元素始终在顶层
}

// 添加：优化文档流
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

// 添加弹窗相关样式
:deep(.el-dialog__body) {
  padding: 10px 20px;
}

// 添加多月视图的样式调整
:deep(.fc-multiMonthYear-view) {
  padding: 10px;
  
  .fc-multimonth-title {
    font-size: 1.2em;
    padding: 8px;
    text-align: center;
  }
  
  .fc-multimonth {
    border: 1px solid #ebeef5;
    border-radius: 4px;
    margin: 5px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  }
}
</style>

